package site.yunnong.atvris.portal.service.impl;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import site.yunnong.atvris.common.utils.ListUtils;
import site.yunnong.atvris.dao.domain.Tags;
import site.yunnong.atvris.dao.domain.VideoTags;
import site.yunnong.atvris.service.TagsService;
import site.yunnong.atvris.service.VideoTagsService;
import site.yunnong.atvris.common.dto.TagsRandomQueryParam;
import site.yunnong.atvris.portal.service.FrontTagsService;
import site.yunnong.atvris.service.vo.TagsVO;
import site.yunnong.atvris.service.vo.VideoTagsVO;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zjh
 * @date 2021/8/14 22:25
 */
@Service
public class FrontTagsServiceImpl implements FrontTagsService {

    @Resource
    private TagsService tagsService;
    @Resource
    private VideoTagsService videoTagsService;

    @Override
    public List<TagsVO> queryPage(TagsRandomQueryParam param) {
        List<Tags> allTags = tagsService.queryAll();
        // 随机获取
        List<Tags> tags = ListUtils.getRandomList(allTags, param.getPageSize());
        tags.sort(Comparator.comparingInt(Tags::getSort));
        return Optional.of(tags).orElse(Lists.newArrayList())
                .stream().map(this::buildTagsVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<TagsVO> queryAll() {
        List<Tags> tags = tagsService.queryAll();
        return Optional.of(tags).orElse(Lists.newArrayList())
                .stream().map(this::buildTagsVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<VideoTagsVO> queryVideoTags(Long uvid) {
        List<VideoTags> list = videoTagsService.queryVideoTagsByUvid(uvid);
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        return list.stream().map(this::buildVideoTagsVO).collect(Collectors.toList());
    }

    private TagsVO buildTagsVO(Tags tag) {
        return TagsVO.builder()
                .id(tag.getId())
                .name(tag.getName())
                .build();
    }

    private VideoTagsVO buildVideoTagsVO(VideoTags videoTags) {
        VideoTagsVO vo = new VideoTagsVO();
        BeanUtils.copyProperties(videoTags, vo);
        return vo;
    }
}
